<template>
  <yd-layout>
    <div id="cart" class="cart">
      <!-- header -->
      <yd-navbar slot="navbar" fixed>
        <router-link to="/home" slot="left">
          <yd-navbar-back-icon></yd-navbar-back-icon>
        </router-link>
        <span slot="center" class="header_text" style="font-size:18px">购物车</span>

        <span slot="right"><a @click="edit()">{{editTxt}}</a></span>

      </yd-navbar>
      <!-- content -->
      <div class="content-cart" fixed slot>
        <div>
          <yd-checklist v-model="checklist3" :label="false" :callback="change">
            <yd-checklist-item v-for="(item, idx) in list" :val="idx">
              <yd-flexbox style="padding: 15px 0;">
                <img :src="item.productMainImage" class="demo-checklist-img">
                <yd-flexbox-item align="top">
                  <span class="cart-text">{{item.productName}}</span><br/>
                  <span class="cart-text" style="color: #ccc;">颜色：粉色系  &emsp;  尺码：s</span><br/>
                  <span class="cart-text">
                    ￥{{item.productTotalPrice}} 
                  <span style="float:right">
                    <a class="num" @click="update(item,'desc')">-</a>
                    <!----><span>&emsp;{{item.quantity}} &emsp;</span>
                  <a class="num" @click="update(item,'plus')">+</a>
                  </span>
                  </span>
                  <div></div>
                </yd-flexbox-item>
              </yd-flexbox>
            </yd-checklist-item>
          </yd-checklist>
          <div class="selectAll">
            <div class="btnAll">
              <label for="mybtn">
              <input id="mybtn" class="mybtn" type="checkbox" @click="checkAll()"><b></b>全选</input>
            </label>
            </div>
            <div class="text" v-show="isShow">
              <span>合计：{{cartTotalPrice}}￥</span>
            </div>
            <yd-button type="danger" @click.native="del()">{{this.mybtn}}</yd-button>
          </div>

        </div>

      </div>

      <!-- footer -->
      <v-footer></v-footer>
    </div>
  </yd-layout>
</template>

<script>
  import baseService from '../axios/'
  export default {
    name: 'cart',
    data() {
      return {
        message: '购物车',
        allId: [], //所有商品序号，用于全选功能
        checklist3: this.$store.store.state.cartClickList, //选中商品序号
        clickIds: [], //选中商品id
        clickList: [], //选中商品数据
        myCheck: false, //全选按钮状态
        isShow: true,
        mybtn: "去结算",
        editTxt: "编辑",
        count: 0, //数量
        cartTotalPrice: 0, //选中总价
        allCheckPrice: 0, //选中所有总价
        value: [],
        list: [{
          productMainImage: 'http://image.mall.com/86a2d057-df32-4141-83c0-8443bf2e9fcb.jpg',
          productName: '春夏新款女装',
          productSubtitle: '',
          productTotalPrice: '68.75',
          quantity: '1',
          productId: ''
        }]
      }
    },
    computed: {
      carGoodsNum() {
        return this.$store.store.state.cartGoodsNum
      },
      pageId() {
        return this.$store.store.state.pageId
      },
      orderGoodsIds(){
        return this.$store.store.state.orderGoodsIds
      },
      cartbuy(){
        return this.$store.store.state.cartbuy
      }
    },
    created() {
      let id = "cart";
      this.setpageId(id);
      this.doLogin()
      
    },
    mounted() {
      this.getlist()
    },
    methods: {
      setpageId(id) {
        this.$store.store.commit('setpageId', id)
      },
      edit() {
        console.log(this.isShow);
        this.isShow = !this.isShow;
        console.log(this.isShow);

        if (this.isShow == false) {
          this.editTxt = "完成"
          this.mybtn = "删除"
        } else {
          this.editTxt = "编辑"
          this.mybtn = "去结算"
        }
      },
      doLogin() {
        if (this.$store.store.state.userInfo.id == undefined) {
          this.$dialog.confirm({
            mes: "用户未登录，请先登录 ！",
            opts: [{
                txt: '暂不登录，随便逛逛',
                // stay: true,
                color: '#888',
                callback: () => {
                  this.$router.push({
                    path: '/'
                  })
                }
              },
              {
                txt: '确定',
                color: true,
                callback: () => {
                  this.$router.push({
                    path: '/user/login'
                  })
                }
              }
            ]
          });
        }
      },
      getlist() {
        baseService.post('/cart/list.do').then((res) => {
          if (res.data.status == 0) {
            //打印服务端传过来的数据
            console.log(res.data.data)
            //购物车商品列表的长度赋值给list的长度
            this.list.length = res.data.data.cartProductVoList.length;
            //购物车商品列表的长度放在store缓存，其他页面使用
            this.$store.store.state.cartGoodsNum = this.list.length;
            //所有商品总价赋值给——————————————allCheckPrice
            this.allCheckPrice = res.data.data.cartTotalPrice;
            //购物车商品列表序号保存在——————————————allId里
            this.allId = []
            for (let i = 0; i < this.list.length; i++) {
              this.allId.push(i);
            }
            //购物车商品列表赋给list
            this.list = res.data.data.cartProductVoList;
            //总价初始化
            let idx = this.$store.store.state.cartClickList;
            this.cartTotalPrice = this.list[idx].productTotalPrice;
            //初始化全选按钮
            console.log("panduan",this.allId.length);
            if(this.allId.length == 1){
              let btn = document.getElementById('mybtn');
              btn.checked = true;
            }
          }
        }).catch((err) => {

        })
      },
      del() {
        if (this.mybtn == "删除" && this.checklist3.length > 0) {
          this.$dialog.confirm({
            title: '',
            mes: '确定删除吗？',
            opts: () => {
              console.log(this.checklist3);
              this.clickIds = []
              for (let i = 0; i < this.checklist3.length; i++) {
                let idx = this.checklist3[i]
                this.clickIds.push(this.list[idx].productId)
              }
              console.log(this.clickIds);
              let param = new URLSearchParams();
              param.append("productIds", this.clickIds);
              baseService.post('/cart/delete.do', param).then((res) => {
                console.log("-----------删除成功--------")
                this.$dialog.toast({
                  mes: '删除成功!',
                  timeout: 1000
                });
                this.getlist();
              })
            }
          });
        }
        if (this.mybtn == "去结算" && this.checklist3.length > 0) {
          this.$store.store.state.cartbuy = true;
          console.log("购物车结算状态：",this.$store.store.state.cartbuy)
          //选中商品列表保存在store缓存中
          this.clickList = []
          this.clickIds = []
          for (let i = 0; i < this.checklist3.length; i++) {
            let idx = this.checklist3[i]
            this.clickList.push(this.list[idx])
            this.clickIds.push(this.list[idx].id)
          }
          this.$store.store.state.cartClickList = this.clickList;
          this.$store.store.state.orderGoodsIds = this.clickIds;
          this.$router.push({
            path: '/order/confirmOrder'
          })
        }
      },
      update(item, fun) {
        if (item.quantity >= 0) {
          //改变数量
          fun === 'plus' ? item.quantity++ : item.quantity--;
          //如果选中且改变数量，重新计算总价
          if (this.checklist3.length > 0) {
            fun === 'plus' ? this.cartTotalPrice += item.productPrice : this.cartTotalPrice -= item.productPrice
          }
          let param = new URLSearchParams();
          param.append("productId", item.productId);
          param.append("count", item.quantity);
          baseService.post('/cart/update.do', param).then((res) => {
            console.log("-----------数量更新成功--------")
            this.getlist();
          })
        }
      },
      change(value) {
        //将选中列表序号保存在————————————checklist3中
        this.checklist3 = value;
        let btn = document.getElementById('mybtn');
        //如果选中的长度=列表长度，即全选，全选按钮勾选
        if (value.length == this.list.length) {
          btn.checked = true;
          this.cartTotalPrice = this.allCheckPrice;
          //将全选按钮的勾选状态报讯在——————————myCheck中
          this.myCheck = btn.checked;
        } else {
          btn.checked = false;
          this.cartTotalPrice = 0;
          for (let i = 0, a; i < value.length; i++) {
            a = value[i];
            this.cartTotalPrice = this.cartTotalPrice + this.list[a].productTotalPrice
            console.log(this.list[a].productTotalPrice)
            console.log(this.cartTotalPrice)
          }
        }
      },
      checkAll() {
        console.log(this.myCheck)
        //全选按钮选中状态置反
        this.myCheck = !this.myCheck;
        //根据按钮选中状态给全选按钮赋值
        let btn = document.getElementById('mybtn');
        btn.checked = this.myCheck;
        console.log(btn.checked)
        if (btn.checked == true) {
          this.checklist3 = this.allId;
          this.cartTotalPrice = this.allCheckPrice;
          return;
        }
        if (btn.checked == false) {
          this.checklist3 = [];
          this.cartTotalPrice = 0;
          return;
        }
        console.log(this.checklist3)
      }
    },
    destroyed (){
      this.$store.store.state.cartClickList = []
    }
  }

</script>

<style scoped>
  .cart .content-cart {
    margin-top: 12%;
    width: 100%;
    height: 78%;
    position: fixed;
    overflow-y: auto;
  }
  /* 列表样式 */

  .demo-checklist-img {
    height: 100px;
  }

  .yd-flexbox-item-start {
    text-align: left;
  }

  .cart-text {
    display: block;
    margin-left: 5px;
  }

  .cart-text .num {
    border: solid 1px #ccc;
    padding: 5px;
  }
  /* 全选 */

  .cart .content-cart .selectAll {
    z-index: 5 !important;
    width: 100% !important;
    position: fixed !important;
    bottom: 8% !important;
    height: 8% !important;

    text-align: left !important;
    border-top: solid 1px #e4e4e4 !important;
    background-color: #fff !important;
  }

  .selectAll .yd-checkbox {
    margin-left: 5% !important;
    height: 80%;
    display: inline-block;
  }



  .selectAll .text {
    display: inline-block;
    line-height: 50px;
    width: 40%;
    text-align: right;
  }

  .selectAll .yd-btn {
    display: inline-block;
    float: right;
    margin: 1.5%;
    margin-top: auto 5px !important;
    height: 80%;
    font-size: 13px;
  }

  .selectAll .btnAll {
    height: 100%;
    display: inline-block;

    width: 80px;
    font-size: 15px;
    line-height: 50px;
  }
  /*自定义样式的checkbox*/

  label {
    display: block;
    height: 100% !important;
    padding: 0 !important;
    margin: 3px!important;
  }
  /*旧按钮处理*/

  input {
    visibility: hidden;
    /*隐藏掉默认样式的checkbox,但仍然保留占有空间 */
    display: none;
    /*隐藏并销毁占有空间*/
  }
  /*新按钮样式*/

  b {
    cursor: pointer;
    display: inline-block;
    /*行内显示，并且可以撑起空间*/
    width: 20px;
    height: 20px;
    /*大小*/
    border: solid 1px #ccc !important;
    /*边框样式*/
    border-radius: 10px;
    /*圆角*/
    vertical-align: middle;
    /*水平居中*/
    margin: 5px;
  }
  /*制作对号 */

  b:after {
    opacity: 0;
    /*透明度 */
    content: '';
    position: absolute;
    width: 13px;
    height: 7px;
    /*大小*/
    background: transparent;
    /*方块填充色*/
    top: 24px;
    left: 12px;
    /*定位*/
    border: 2px solid white;
    /*边框效果*/
    border-top: none;
    border-right: none;
    /*生成对号*/
    transform: rotate(-45deg) scale(0);
    /* 旋转缩放 */
    transition: all 0.3s;
    /*动画延时*/
  }
  /*新按钮点击时样式*/

  input:checked+b {
    background-color: rgb(76, 216, 100);
  }
  /*点击时对号效果*/

  input:checked+b:after {
    transform: rotate(-45deg) scale(1);
    opacity: 1;
  }

</style>
